import React, { useEffect, useRef } from 'react';
import { ModalForm, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import { addRoleFun, getRoleByIdFun, updateRoleFun } from '@/services/ant-design-pro/systemApi';
import { message } from 'antd';

function RoleModalForm(prop) {
  const roleFormRef = useRef<ProFormInstance>();

  useEffect(() => {
    if (prop.currentRow && prop.modalVisit) {
      getRoleByIdFun(prop.currentRow?.roleId).then((res) => {
        roleFormRef.current?.setFieldsValue(res.data);
      });
    }
  }, [prop.currentRow]);

  // 点击保存触发
  const onFinish = async (values) => {
    let data = {
      ...prop.currentRow,
      ...values,
    };
    if (prop.currentRow) {
      updateRoleFun(data).then((res) => {
        message.success(res.msg);
        prop.onCancel(true);
      });
    } else {
      addRoleFun(data).then((res) => {
        message.success(res.msg);
        prop.onCancel(true);
      });
    }
  };

  return (
    <>
      <ModalForm
        formRef={roleFormRef}
        title="新建用户"
        open={prop.modalVisit}
        onFinish={onFinish}
        width={'600px'}
        layout={'vertical'}
        modalProps={{
          destroyOnClose: true,
          onCancel: () => prop.onCancel(),
        }}
      >
        <ProFormText
          name="roleName"
          label="角色名称"
          placeholder="请输入角色名称"
          rules={[{ required: true, message: '请输入角色名称' }]}
        />

        <ProFormText
          name="roleKey"
          label="角色Key"
          placeholder="请输入角色Key"
          rules={[{ required: true, message: '请输入角色Key' }]}
        />
      </ModalForm>
    </>
  );
}

export default RoleModalForm;
